//
//  KDFocusListController.m
//  YuQingXiaoFang
//
//  Created by wangdongdong on 18/6/15.
//  Copyright © 2018年 KDTech. All rights reserved.
//

#import "KDFocusListController.h"
#import "KDFocusListController.h"


#import "KDBaseListParam.h"

#import "KDTabBarController.h"

#import "KDFocusListParam.h"
#import "KDFocusRequestTool.h"
#import "KDFocusListCellModel.h"
#import "KDFocusListCell.h"

#import "KDFocusListResult.h"
#import "KDFocusListCellModelFrame.h"
#import "KDHomeViewController.h"
#import "AlertTableView.h"
#import "KDAccountTool.h"
 
@interface KDFocusListController ()<UITableViewDelegate,UITableViewDataSource,KDFocusListCellDelegate>
/**
 *  所有主题数据的集合
 */
@property (nonatomic, strong) NSArray * themeArr;
/**  <#Description#> */
@property (nonatomic, strong) NSArray *infoArr;
/**  <#Description#> */
@property (nonatomic, weak) UITableView *currentTabV;
/**
 *  加载第几页
 */
@property (nonatomic, copy) NSString *page;
@property (nonatomic,strong) NSArray *modelFrames;

@property (nonatomic,retain) NSDateFormatter *fmt;
@end
static CGFloat const tableViewH = 75;

@implementation KDFocusListController
#pragma mark - 懒加载区
- (NSString *)page
{
    if (!_page) {
        _page = @"1";
    }
    return _page;
}
- (NSArray *)infoArr
{
    if (!_infoArr) {
        _infoArr = [NSArray array];
    }
    return _infoArr;
}
#pragma mark -生命周期区
- (void)viewDidLoad {
    [super viewDidLoad];
    //[self setupNavBar];
    [self setUpTableView];
}

#pragma mark - 板块布置区
- (void)setUpTableView
{
    
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0  , 0, screenW, screenH-20-navH-tabH) style:UITableViewStylePlain];
    
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tag = 1000;
    tableView.tableFooterView = [UIView new];
    tableView.separatorColor = BackGroundColor;
    tableView.backgroundColor = BackGroundColor;
    tableView.rowHeight = tableViewH;
    [tableView setSeparatorColor:[UIColor grayColor]];
    
    //1.调整(iOS8以上)tableView边距(与上面第2步等效,二选一即可)
    if ([tableView respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        tableView.preservesSuperviewLayoutMargins = NO;
    }
    //2.调整(iOS8以上)view边距
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if (!iOS7) {
        tableView.estimatedRowHeight = tableViewH;
    }
    self.currentTabV = tableView;
    [self.view addSubview:tableView];
    //UINib *xib =[UINib nibWithNibName:@"KDFocusListCell" bundle:nil] ;
    
    //[tableView registerNib:xib forCellReuseIdentifier:@"KDFocusListCell"];
    
    tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadDetailData)];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreDetailData)];
    [footer setTitle:@"" forState:MJRefreshStateIdle];
    // 设置footer
    self.currentTabV.footer = footer;
    [self.currentTabV.header beginRefreshing];
}
- (void)setupNavBar{
    //self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"退出" style:UIBarButtonItemStyleDone target:self action: @selector(loginoutSS:) ];
    
    //KDAccount *account = [KDAccountTool account];
    //NSString *time =[self.fmt stringFromDate:[[NSDate alloc] init]];
    //NSString *userNameAndTime=[NSString stringWithFormat:@"%@ %@",account.userName,time];
    //self.navigationItem.title=userNameAndTime;
    
}
#pragma mark - 事件点击区
- (void)leftItemClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 网络请求区
- (void)loadDetailData{
    //WS(ws);
    KDFocusListParam *param = [[KDFocusListParam alloc]init];
    KDAccount *account = [KDAccountTool account];
    param.apppersonid= [NSString stringWithFormat:@"%ld",account.userId];
    param.pageSize = @"20";
    self.page = @"1";
    param.pageNo = self.page;
    
    [KDFocusRequestTool getFocusListWithParam:param success:^(KDFocusListResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            self.infoArr = [KDFocusListCellModel objectArrayWithKeyValuesArray:responseObejct.data];
            
            // 创建frame模型对象
            NSMutableArray *modelFrameArray = [NSMutableArray array];
            for (KDFocusListCellModel *model in _infoArr) {
                KDFocusListCellModelFrame *modelFrame = [[KDFocusListCellModelFrame alloc] init];
                // 传递微博模型数据
                modelFrame.model = model;
                [modelFrameArray addObject:modelFrame];
            }
            
            // 赋值
            self.modelFrames = modelFrameArray;
            
            
            [self.currentTabV.header endRefreshing];
            [self.currentTabV reloadData];
        }else if ([responseObejct.code isEqualToString:@"E040110000001"]){
            [self.currentTabV.header endRefreshing];
            [self.navigationController dismissViewControllerAnimated:NO completion:^{
                KDNewfeatureController *new = [[KDNewfeatureController alloc]init];
                __block KDTabBarController*ctr = (KDTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                [UIApplication sharedApplication].keyWindow.rootViewController = new;
                [ctr removeObserver];
                [ctr removeFromParentViewController];
                ctr = nil;
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
            [self.currentTabV.header endRefreshing];
        }
        
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
        [self.currentTabV.header endRefreshing];
        KDLog(@"%@",error);
        
    }];
}
- (void)loadMoreDetailData{
    
    KDFocusListParam *param = [[KDFocusListParam alloc]init];
    self.page = [NSString stringWithFormat:@"%ld", self.page.integerValue +1];
    KDAccount *account = [KDAccountTool account];
    param.apppersonid= [NSString stringWithFormat:@"%ld",account.userId];
    param.pageNo = self.page;
    param.pageSize = @"20";
   
    [KDFocusRequestTool getFocusListWithParam:param success:^(KDFocusListResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            
            NSArray *arr1 = [KDFocusListCellModel objectArrayWithKeyValuesArray:responseObejct.data];
            if (arr1.count) {
                NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
                [arr addObjectsFromArray:arr1];
                self.infoArr = arr;
                [self.currentTabV.footer endRefreshing];
                [self.currentTabV reloadData];
            }else{
                [self.currentTabV.footer noticeNoMoreData];
            }
            
            
            [self.currentTabV reloadData];
        }else if ([responseObejct.code isEqualToString:@"E040110000001"]){
            [self.currentTabV.footer endRefreshing];
            [self.navigationController dismissViewControllerAnimated:NO completion:^{
                KDNewfeatureController *new = [[KDNewfeatureController alloc]init];
                __block KDTabBarController*ctr = (KDTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                [UIApplication sharedApplication].keyWindow.rootViewController = new;
                [ctr removeObserver];
                [ctr removeFromParentViewController];
                ctr = nil;
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
            [self.currentTabV.footer endRefreshing];
        }
        
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误！" maskType:SVProgressHUDMaskTypeGradient];
        [self.currentTabV.footer endRefreshing];
        KDLog(@"%@",error);
        
    }];
}
//刷新数据
-(void) refreshData{
    [self.currentTabV.header beginRefreshing];
}
#pragma mark - 通知接收区
#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KDFocusListCell *cell = [KDFocusListCell cellWithTableView:tableView];
    //    KDLog(@"waimian%d", indexPath.row);
    cell.delegate = self;
    if (tableView == self.currentTabV)
    {
        cell.delegate = self;
        if (self.infoArr.count != 0)
        {
            cell.modelFrame = self.modelFrames[indexPath.row];
        }
        return cell;
    }else{
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    KDFocusListCellModelFrame *modelFrame=self.modelFrames[indexPath.row];
    return modelFrame.cellHeight;
}

/**
 *  cell被点击了
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.currentTabV) {
        if (self.infoArr.count == 0) {
            return;
        }
        KDFocusListCell *cell = (KDFocusListCell *)[tableView cellForRowAtIndexPath:indexPath];
        NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
        [arr replaceObjectAtIndex:indexPath.row withObject:cell.model];
        self.infoArr = arr;
        //WS(ws);
        /**
         [self getNewsModelWithID:cell.model.newsId success:^(KDSubscribCellModel *model) {
         KDDetailSubscribController *singleCtrl = [[KDDetailSubscribController alloc]init];
         singleCtrl.delegate = ws;
         singleCtrl.model = model;
         
         
         [ws.navigationController pushViewController:singleCtrl animated:YES];
         
         }];
         */
        
    }
}

/**
 *  通过ID，请求获取一个本信息的所有细节
 *
 *  @param ID 信息ID
 */
/**
 - (void)getNewsModelWithID:(NSString *)ID success:(void (^)(KDSubscribCellModel *model))success{
 
 KDMoveFavorParam *param = [[KDMoveFavorParam alloc]init];
 param.ID = ID;
 [SVProgressHUD showWithStatus:@"加载中…" maskType:SVProgressHUDMaskTypeGradient];
 [KDCollectRequestTool getNewsWithParam:param success:^(KDBaseResult *responseObejct) {
 if ([responseObejct.code isEqualToString:@"1"]) {
 KDSubscribCellModel * model= [KDSubscribCellModel objectWithKeyValues:responseObejct.data];
 [SVProgressHUD dismiss];
 if (model) {
 success(model);
 }else{
 [SVProgressHUD showInfoWithStatus:@"未查询到数据" maskType:SVProgressHUDMaskTypeGradient];
 }
 
 }else{
 [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
 }
 } failure:^(NSError *error) {
 [SVProgressHUD showErrorWithStatus:@"网络错误!" maskType:SVProgressHUDMaskTypeGradient];
 }];
 }
 
 */

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}


/**
 *  取消关注
 *
 *  @param cell
 */

-(void)subscribCell:(KDFocusListCell *)cell cancelBtnClick:(UIButton *)cancelBtn{
    //WS(ws);
    NSMutableArray *arr = [NSMutableArray arrayWithArray:self.infoArr];
    NSIndexPath *ip = [self.currentTabV indexPathForCell:cell];
    KDFocusListParam *param = [[KDFocusListParam alloc]init];
    KDAccount *account = [KDAccountTool account];
    param.apppersonid= [NSString stringWithFormat:@"%ld",account.userId];
    param.newsid=[NSString stringWithFormat:@"%ld",cell.modelFrame.model.newsid];
    param.newstype=[NSString stringWithFormat:@"%ld",cell.modelFrame.model.newstype];
    //param.flag=0;
    [SVProgressHUD showWithStatus:@"删除中..." maskType:SVProgressHUDMaskTypeGradient];
    [KDFocusRequestTool cancelFocusWithParam:param success:^(KDBaseResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            [SVProgressHUD dismiss];
            [arr removeObjectAtIndex:ip.row];
            self.infoArr = arr;
            [self.currentTabV deleteRowsAtIndexPaths:@[ip] withRowAnimation:UITableViewRowAnimationAutomatic];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误!" maskType:SVProgressHUDMaskTypeGradient];
    }];
}

- (NSDateFormatter *)fmt
{
    if (!_fmt) {
        _fmt = [[NSDateFormatter alloc]init];
        _fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];;
        _fmt.dateFormat = @"YYYY-MM-dd HH:mm:ss";
    }
    return _fmt;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end


